<template>
  <div class="defaultAlgoList">
    <a-table :columns="tableColumns" :data-source="dataList" :pagination="false" :loading="loading" @change="tableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'cpu'">
          <div class="noun">
            <span>CPU:{{ record.cpu }}Core</span>
            <span class="mid-line"></span>
            <span>内存:{{ record.memory }}GB</span>
            <span class="mid-line"></span>
            <span>显存:{{ record.gpu }}GB</span>
          </div>
        </template>
        <template v-else-if="column.dataIndex == 'type'">
          <div :class="[record.type && 'type-mark']">
            {{ ALGO_TYPE_OPTIONS.find((item: any) => item.value === record.type)?.label || '/' }}
          </div>
        </template>
        <template v-else-if="column.dataIndex == 'createTime'">
          <div>
            {{ dateFormat(record.createTime) }}
          </div>
        </template>

        <template v-else-if="column.dataIndex === 'tools'">
          <a-dropdown placement="bottom" @click.stop>
            <a-button :data-share="record?.createType === 1" type="text" class="icon-only-btn" @click.stop>
              <i class="iconfont icon-more-line"></i>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly)"
                  class="menu-icon-item"
                  @click="operate(1, record as AlgoType)"
                >
                  编辑
                </a-menu-item>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly)"
                  class="menu-icon-item"
                  @click="operate(2, record as AlgoType)"
                >
                  code
                </a-menu-item>
                <a-menu-item class="menu-icon-item" @click="operate(3, record as AlgoType)"> 训练 </a-menu-item>
                <a-menu-item class="menu-icon-item" @click="operate(4, record as AlgoType)"> 下载 </a-menu-item>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly)"
                  class="menu-icon-item"
                  @click="operate(5, record as AlgoType)"
                >
                  删除
                </a-menu-item>
                <a-menu-item
                  v-if="checkPermissions(record?.createType, record?.readOnly)"
                  class="menu-icon-item"
                  @click="operate(6, record as AlgoType)"
                >
                  分享
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
      </template>
    </a-table>

    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
  </div>

  <delete-confirm-dialog
    v-model:show="showDeleteModal"
    title="确认删除"
    msg="此算法将被删除，不可恢复，请确认操作"
    label="请输入算法名称"
    :confirm-name="selectItem?.name"
    :loading="confirmLoading"
    @ok="onOkDeleteTask"
  />
  <share-modal
    ref="shareModalRef"
    :submit-api="algoDevApi.shareAlgorithm"
    :remove-user-api="algoDevApi.removeAlgorithmShareUser"
    :get-list-api="algoDevApi.getAlgorithmShareList"
  />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { TableProps } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { onMounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import useList from '@/hooks/use-list'
  import { algoDevApi } from '@/services'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'
  import { checkPermissions } from '@/utils/share'

  import { useOpenNotebook } from '../../hooks/use-open-notebook'
  import { ALGO_TYPE_OPTIONS } from '../../options'
  import { AlgoType } from '../types'
  import { useExportListDrawer } from './ExportListDrawer/store'

  const router = useRouter()
  const useNotebook = useOpenNotebook(2)
  const exportListDrawerStore = useExportListDrawer()

  type TableDataType = {
    key: string
    name: string
    age: number
    address: string
  }
  type PageForm = {
    name: string
    type: number | string
    columns: 'updateTime' | 'createTime'
    order: 'desc' | 'asc'
  }
  /**
   * 表格列
   */
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        width: 180
      },
      {
        title: '类型',
        dataIndex: 'type',
        width: 140
      },
      {
        title: '镜像',
        dataIndex: 'imageName',
        width: 200
      },
      {
        title: '框架',
        dataIndex: 'frame',
        width: 80
      },
      {
        title: '资源配置',
        dataIndex: 'cpu',
        width: 300
      },
      {
        title: '描述',
        dataIndex: 'remark'
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        isSort: true,
        width: 160
      },
      {
        title: '操作',
        width: 80,
        dataIndex: 'tools'
      }
    ])
  )

  const { pageForm, dataList, loading, getDataList } = useList<PageForm, AlgoType>(algoDevApi.customAlgoList, {
    name: '',
    type: '',
    columns: 'createTime',
    order: 'desc'
  })
  const tableChange: TableProps<TableDataType>['onChange'] = (pagination, filters, sorter: any) => {
    if (!sorter.order) {
      getDataList({ order: 'desc', columns: 'createTime' })
      return
    }
    const order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getDataList({ offset: 1, order, columns: sorter.field })
  }

  const showDeleteModal = ref(false)
  const selectItem = ref<AlgoType>() //当前选中的应用
  const shareModalRef = ref() // 分享
  const operate = (type: number, item: AlgoType) => {
    switch (type) {
      case 1: // 编辑
        router.push({
          path: `/algo-dev/algo-manage/edit/${item.id}`
        })
        break
      case 2: // code
        useNotebook.checkNotebookStatus(item.id, item.serviceUrl)
        break
      case 3: // 训练
        console.log('训练')
        break
      case 4: // 下载
        exportListDrawerStore.addDownTask(item.id as any as string)
        break
      case 5: // 删除
        selectItem.value = item
        showDeleteModal.value = true
        break
      case 6: // 分享
        shareModalRef.value?.open({
          id: item.id
        })
        break
      default:
        console.log('other')
    }
  }

  // 删除确认
  const { loading: confirmLoading, runAsync: runDel } = useRequest(algoDevApi.delAlgorithm)
  const onOkDeleteTask = async () => {
    await runDel({}, { urlParams: { id: selectItem.value?.id } })
    message.success('操作成功')
    showDeleteModal.value = false
    getDataList()
  }

  onMounted(() => {
    getDataList()
  })

  defineExpose({
    search: (params: PageForm) => {
      if (params) {
        Object.assign(pageForm.value, params)
        getDataList()
      }
    }
  })
</script>

<style lang="less" scoped>
  .type-mark {
    display: inline-block;
    padding: 3px 6px;
    color: #4686ed;
    background: #f2f6fe;
    border: 1px solid @mask1;
    border-radius: 6px;
    line-height: 22px;
  }

  .noun {
    display: flex;
    align-items: center;

    .mid-line {
      display: inline-block;
      margin: 0 4px;
      width: 1px;
      height: 14px;
      background-color: #e8e9eb;
    }
  }
</style>
